# coding=utf-8
import sys
import json
import io
# from playsound import playsound  # 新增播放库导入
import time
from pydub import AudioSegment
from pydub.playback import play

IS_PY3 = sys.version_info.major == 3
if IS_PY3:
    from urllib.request import urlopen
    from urllib.request import Request
    from urllib.error import URLError
    from urllib.parse import urlencode
    from urllib.parse import quote_plus

API_KEY = '*'
SECRET_KEY = '*'

TEXT = "你好，我是思源同学。"

# 发音人选择, 基础音库：0为度小美，1为度小宇，3为度逍遥，4为度丫丫，
# 精品音库：5为度小娇，103为度米朵，106为度博文，110为度小童，111为度小萌，默认为度小美 
PER = 5
# 语速，取值0-15，默认为5中语速
SPD = 6
# 音调，取值0-15，默认为5中语调
PIT = 6
# 音量，取值0-9，默认为5中音量
VOL = 6
# 下载的文件格式, 3：mp3(default) 4： pcm-16k 5： pcm-8k 6. wav
AUE = 3

FORMATS = {3: "mp3", 4: "pcm", 5: "pcm", 6: "wav"}
FORMAT = FORMATS[AUE]

CUID = "123456PYTHON"

TTS_URL = 'http://tsn.baidu.com/text2audio'


class DemoError(Exception):
    pass


"""  TOKEN start """

TOKEN_URL = 'http://aip.baidubce.com/oauth/2.0/token'
SCOPE = 'audio_tts_post'  # 有此scope表示有tts能力，没有请在网页里勾选


def fetch_token():
    print("fetch token begin")
    params = {'grant_type': 'client_credentials',
              'client_id': API_KEY,
              'client_secret': SECRET_KEY}
    post_data = urlencode(params)
    if (IS_PY3):
        post_data = post_data.encode('utf-8')
    req = Request(TOKEN_URL, post_data)
    try:
        start_time = time.time()
        f = urlopen(req, timeout=5)
        print("urlopen耗时: %s秒" % (time.time() - start_time))

        start_time = time.time()
        result_str = f.read()
        print("f.read()耗时: %s秒" % (time.time() - start_time))

        start_time = time.time()
        headers = dict((name.lower(), value) for name, value in f.headers.items())
        print("头部处理耗时: %s秒" % (time.time() - start_time))

        has_error = ('content-type' not in headers.keys() or headers['content-type'].find('audio/') < 0)
    except URLError as err:
        print('token http response http code : ' + str(err.code))
        result_str = err.read()
        has_error = True
        
    if (IS_PY3):
        result_str = result_str.decode()

    print(result_str)
    result = json.loads(result_str)
    print(result)
    if ('access_token' in result.keys() and 'scope' in result.keys()):
        if not SCOPE in result['scope'].split(' '):
            raise DemoError('scope is not correct')
        print('SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))
        return result['access_token']
    else:
        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')


def TTS_By_BaiduAPI(textInput):
    TEXT = textInput
    token = '24.8d23bd04d8d7a532bb57e798d3f2044d.2592000.1745310052.282335-118175278'
    tex = quote_plus(TEXT)  # URL-encoded text
    print(tex)
    
    params = {
        'tok': token,
        'tex': tex,
        'per': PER,
        'spd': SPD,
        'pit': PIT,
        'vol': VOL,
        'aue': AUE,
        'cuid': CUID,
        'lan': 'zh',
        'ctp': 1
    }
    data = urlencode(params)
    # print('Test URL: ' + TTS_URL + '?' + data)

    req = Request(TTS_URL, data.encode('utf-8'))
    print("\nreq: ", req)
    has_error = False

    try:
        start_time = time.time()
        f = urlopen(req)
        print("urlopen耗时: %s秒" % (time.time() - start_time))

        start_time = time.time()
        result_str = f.read()
        print("f.read()耗时: %s秒" % (time.time() - start_time))

        start_time = time.time()
        headers = dict((name.lower(), value) for name, value in f.headers.items())
        print("头部处理耗时: %s秒" % (time.time() - start_time))

        # Check if the returned content is audio
        has_error = ('content-type' not in headers.keys() or headers['content-type'].find('audio/') < 0)
    except URLError as err:
        print('HTTP响应错误代码: ' + str(err.code))
        result_str = err.read()
        has_error = True

    if not has_error:
        try:
            print("正在播放合成音频...")
            # Use BytesIO to avoid file I/O; specify format if needed (e.g., "mp3")
            audio_data = io.BytesIO(result_str)
            sound = AudioSegment.from_file(audio_data, format="mp3")
            play(sound)
            print("播放结束")
        except Exception as e:
            print(f"音频播放失败：{str(e)}（请检查音频文件格式或播放库依赖）")
    else:
        if IS_PY3:
            result_str = str(result_str, 'utf-8')
        print("TTS API 错误:" + result_str)

    print("-------------------\n")

    
    
# TTS_By_BaiduAPI("好的，思源同学为你执行任务。")